package com.mmall.example.aqs.sempaphore;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * semaphore 一次获取多个许可
 * Created by megan on 2018/4/30.
 */
@Slf4j
public class SemaphoreExample1 {
    /** 200个线程 **/
    private static int threadCount = 200;

    public static void main(String[] args) throws Exception {
        /** 定义一个线程池 **/
        ExecutorService exec = Executors.newCachedThreadPool();

        /** 允许并发数为 3 **/
        Semaphore semaphore = new Semaphore(3);

        for(int i = 0 ; i < threadCount; i++){
            final int threadNum = i;
            exec.execute(() -> {
                try {
                    //获取一个许可
                    semaphore.acquire(3);

                    test(threadNum);

                    //释放一个许可
                    semaphore.release(3);
                } catch (Exception e) {
                    log.info("exception:{}",e);
                }
            });
        }
        exec.shutdown();
    }

    private static void test(int threadNum) throws Exception {
        log.info("{}",threadNum);
        Thread.sleep(1000);
    }
}
